package cn.htsyb.synergy.orm.jpa.criterion;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;

/**
 * 排序表达式
 *
 * @author lakeside hubin_yuan.410@hotmail.com
 * @version V1.0.0
 * @date 2022/5/11
 * @since 1.0
 */
@Setter
@Getter
@Schema(description = "查询排序")
@NoArgsConstructor
public class OrderExpress implements Serializable {
    private String field;
    private Direction direction = Direction.ASC;

    public OrderExpress(String field) {
        this.field = field;
    }

    public OrderExpress(String field, Direction direction) {
        this.field = field;
        this.direction = direction;
    }

    /**
     * @param orderContent 示例：field,field2 desc,field3 asc
     * @return
     */
    public static List<OrderExpress> parseOrderParam(String orderContent) {
        List<OrderExpress> orderList = new LinkedList<>();
        if (!StringUtils.isEmpty(orderContent)) {
            String[] orderArr = orderContent.split(",");
            for (String order : orderArr) {
                if (!StringUtils.isEmpty(order)) {
                    String[] sortBy = order.split("\\s");
                    if (sortBy.length >= 2 && !StringUtils.isEmpty(sortBy[1])) {
                        orderList.add(new OrderExpress(sortBy[0], Direction.valueOf(sortBy[1])));
                    } else {
                        orderList.add(new OrderExpress(sortBy[0]));
                    }
                }
            }
        }
        return orderList;
    }

    public enum Direction {
        ASC("asc", "升序排列"),
        DESC("desc", "降序排列");

        private final String value;
        private final String label;


        Direction(String value, String label) {
            this.value = value;
            this.label = label;
        }

        public String getLabel() {
            return label;
        }

        public String getValue() {
            return this.value;
        }

        public boolean isAscending() {
            return this.equals(ASC);
        }

        public boolean isDescending() {
            return this.equals(DESC);
        }
    }
}
